package com.exam.online.system.service.impl;

import com.exam.online.system.dao.CourseDAO;
import com.exam.online.system.dao.TeacherCourseDAO;
import com.exam.online.system.entity.Course;
import com.exam.online.system.model.ConditionQuestionModel;
import com.exam.online.system.service.ConditionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuzhen
 * @date 2019/5/6
 */
@Service
public class ConditionServiceImpl implements ConditionService {

    @Autowired
    private TeacherCourseDAO teacherCourseDAO;
    @Autowired
    private CourseDAO courseDAO;

    @Override
    public List<ConditionQuestionModel> findConditionsByTeacherId(Integer teacherId) {
        List<Integer> courseIds = teacherCourseDAO.selectByTeacherId(teacherId);
        Map<Integer, List<String>> grade2CourseMap = new HashMap<>();
        for (Integer courseId : courseIds) {
            Course course = courseDAO.selectByPrimaryKey(courseId);
            if (course!=null){
                List<String> courses = grade2CourseMap.computeIfAbsent(course.getGrade(), k -> new ArrayList<>());
                if (!courses.contains(course.getCourseName())) {
                    courses.add(course.getCourseName());
                }
            }

        }
        List<ConditionQuestionModel> conditionQuestionModels = new ArrayList<>();
        grade2CourseMap.forEach((g, c) -> {
            ConditionQuestionModel conditionQuestionModel = new ConditionQuestionModel();
            conditionQuestionModel.setGradeId(g);
            conditionQuestionModel.setCourseNames(c);
            conditionQuestionModels.add(conditionQuestionModel);
        });
        return conditionQuestionModels;
    }

    @Override
    public List<Course> findCourseByTeacherId(Integer teacherId) {
        List<Integer> courseIds = teacherCourseDAO.selectByTeacherId(teacherId);
        List<Course> courses = new ArrayList<>();
        for (Integer courseId : courseIds) {
            Course course = courseDAO.selectByPrimaryKey(courseId);
            if (course != null) {
                courses.add(course);
            }
        }
        return courses;
    }

    @Override
    public List<Course> findCourseByGrade(Integer gradeId) {
        return courseDAO.selectByGradeId(gradeId);
    }
}
